/**
 *
 */
package com.googlecode.pkchat.pkserver;

import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Enumeration;
import java.util.Hashtable;

/**
 * @author Simon Pratt
 *
 */
public class Server {

	ServerSocket ss;

	private Hashtable outputStreams;

	/**
	 *
	 */
	public Server(int port) throws IOException {
		outputStreams = new Hashtable();
		listen(port);
	}

	private void listen(int port) throws IOException{
		ss = new ServerSocket(port);
		System.out.println("Listening on "+ss);
		while(true){
			UserSocket s = (UserSocket)ss.accept();
			System.out.println("Connection from "+s);
			DataOutputStream dout = new DataOutputStream(s.getOutputStream());
			outputStreams.put(s,dout);
			new ServerThread(this,s);
		}
	}

	Enumeration getOutputStreams(){
		return outputStreams.elements();
	}

	void sendToAll(String message){
		synchronized(outputStreams){
			for(Enumeration e = getOutputStreams();e.hasMoreElements();){
				DataOutputStream dout = (DataOutputStream) e.nextElement();

				try{
					dout.writeUTF(message);
				}
				catch(IOException ioe){
					System.out.println(ioe);
				}
			}
		}
	}

	void removeConnection(Socket socket){
		synchronized(outputStreams){
			outputStreams.remove(socket);
			try{
				socket.close();
			}catch(Exception e){
				System.out.println("Error closing socket "+socket);
				e.printStackTrace();
			}
		}
	}

	void changeName(Socket oldName,Socket newName){
		DataOutputStream dout = (DataOutputStream)outputStreams.get(oldName);
		outputStreams.put(newName,dout);
		outputStreams.remove(oldName);
	}
}
